import 'dart:async';
import 'dart:convert';

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:banner_carousel/banner_carousel.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_loading_button/easy_loading_button.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:glass_kit/glass_kit.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hambuk/constant/color_constant.dart';
import 'package:hambuk/constant/screen_constant.dart';
import 'package:hambuk/screen/more_video.dart';
import 'package:hambuk/screen/video_player.dart';
import 'package:hambuk/service/HttpService.dart';
import 'package:http/http.dart';
import 'package:material_dialogs/dialogs.dart';
import 'package:radio_group_v2/radio_group_v2.dart';
import 'package:url_launcher/url_launcher.dart';

import '../config/apiConfig.dart';
import '../model/FilmModel.dart';
import '../util/ApiUri.dart';
import '../widget/AnimSearchBar.dart';
import '../widget/banner_images.dart';

class AltasHome extends StatefulWidget {
  const AltasHome({super.key});

  @override
  State<AltasHome> createState() => _AltasHomeState();
}

class _AltasHomeState extends State<AltasHome> {
  /* Service */
  final HttpService httpService = HttpService();

  /* 当前view状态 用于-》下拉加载 */
  final ScrollController scrollController = ScrollController();

  /*电影数据列表*/
  final List<FilmModel> filmList = [];

  /*图片缓存*/
  ImageCache imageCache = PaintingBinding.instance.imageCache;

  /*搜索框*/
  TextEditingController textController = TextEditingController();

  /*变量*/
  bool isLoading = false;
  bool isAdmin = false;
  int listCount = 0;

  /*电影参数*/
  int currentPage = 0;
  int category = -1;
  int contentType = -1;
  int sortType = -1;
  int year = -1;

  /*变化判断*/
  late int previousCategory = -1;
  late int previousContentType = -1;
  late int previousSortType = -1;
  late int previousYear = -1;

  /*软件下载地址*/
  late String APP_URL = 'https://hambuk.jfkj.xyz';

  /*获取电影数据*/
  Future<void> _loadMoreData() async {
    //print("++前" + currentPage.toString());
    currentPage++;
    //print("++后" + currentPage.toString());
    final newItems = await httpService.getAllFilm(
        currentPage, category, contentType, sortType, year);
    if (newItems != null) {
      filmList.addAll(newItems);
      if (newItems.length < 9) {
        setState(() {
          listCount += newItems.length;
          isLoading = false;
        });
      } else {
        setState(() {
          listCount += 9;
          isLoading = true;
        });
      }
    } else {
      setState(() {
        isLoading = false;
      });
    }
  }

  /*获取配置数据*/
  dynamic responseData;

  Future<void> getData() async {
    String filmApi = "/uyapi/file_text.php";
    /* 参数 */
    final params = {
      "keeper": ApiConfig.KEEPER,
      "api": ApiConfig.APPID,
      "title": "data",
    };
    Response response = await post(
        ApiUri().apiUriHost("https://uyclouds.com", filmApi),
        body: params);
    if (response.statusCode == 200) {
      responseData = json.decode(response.body);
      ApiConfig().setToken(responseData['token']);
      ApiConfig().setNotice(responseData['notice']);
      ApiConfig().setOpenID(responseData['openID']);
      setState(() {
        Timer(const Duration(milliseconds: 1500), () {
          _loadMoreData();
          APP_URL = responseData['APP_URL'];
          isAdmin = true;
        });
      });
    } else {
      throw Exception('Failed to fetch video URL');
    }
  }

  /*加载更多*/
  onButtonPressed() async {
    await Future.delayed(const Duration(milliseconds: 1500), () => 42);
    return () {
      _loadMoreData();
    };
  }

  /*初始化*/
  @override
  void initState() {
    getData();
    // 给列表滚动添加监听
    /*scrollController.addListener(() {
      // 滑动到底部的判断
      if (scrollController.position.pixels >=
          scrollController.position.maxScrollExtent) {
        // 开始加载数据
        setState(() {
          _loadMoreData(); //加载数据
        });
      }
    });*/
    super.initState();
  }

  /*销毁*/
  @override
  void dispose() {
    // 组件销毁时，释放资源
    scrollController.dispose();
    textController.dispose();
    super.dispose();
  }

  /*字符串截取*/
  String Strs(String s) {
    int maxCharacters = 10; // 设置最大字数
    if (s.length > maxCharacters) {
      s = '${s.substring(0, maxCharacters - 6)}..';
    }
    return s;
  }

  /*UI构建*/
  @override
  Widget build(BuildContext context) {
    /* 模式设置 SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);*/
    /* 背景颜色设置 */
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
    ));
    // 隐藏状态栏并全屏显示
    final screenCons = ScreenConstants(context);
    /*最多内存缓存设置*/
    imageCache.maximumSize = 300;
    if (isAdmin) {
      return ClipRect(
        child: Scaffold(
          body: Column(
            children: [
              Flexible(
                child: Stack(
                  children: [
                    _banner(screenCons.screenHeight, screenCons.screenWidth),
                    _appBar(),
                  ],
                ),
              ),
            ],
          ),
        ),
      );
    } else {
      return Scaffold(
        body: Column(
          children: [
            Flexible(
              child: Stack(
                children: [
                  Center(
                      child: Text(
                    BannerImages.appName,
                    style: TextStyle(
                      fontFamily: 'MainFont',
                      color: ColorTween(
                        begin: const Color(0xFFED1D24),
                        end: const Color(0xFFED1F69),
                      ).lerp(0.5),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ))
                ],
              ),
            ),
          ],
        ),
      );
    }
  }

  /* 顶部Bar */
  Widget _appBar() {
    return ClipRect(
      child: GlassContainer(
        height: kIsWeb ? 80 : 120,
        width: double.maxFinite,
        borderColor: Colors.transparent,
        gradient: LinearGradient(
          colors: [
            Colors.white.withOpacity(0.1),
            Colors.white.withOpacity(0.1),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderGradient: LinearGradient(
          colors: [
            Colors.white.withOpacity(0.1),
            Colors.white.withOpacity(0.1),
            Colors.lightBlueAccent.withOpacity(0.1),
            Colors.lightBlueAccent.withOpacity(0.1)
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          stops: const [0.0, 0.39, 0.40, 1.0],
        ),
        blur: 5,
        alignment: Alignment.center,
        child: Container(
          color: Colors.transparent,
          margin:
              const EdgeInsets.only(top: kIsWeb ? 0 : 40, left: 20, right: 20),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    BannerImages.appBigName,
                    style: TextStyle(
                      fontFamily: 'MainFont',
                      color: ColorTween(
                        begin: const Color(0xFFED1D24),
                        end: const Color(0xFFED1F69),
                      ).lerp(0.5),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              Align(
                alignment: Alignment.centerRight,
                child: AnimSearchBar(
                  width: 150,
                  helpText: "...",
                  color: const Color(0x33ED1D24),
                  textController: textController,
                  rtl: true,
                  textFieldColor: const Color(0x33ED1D24),
                  textFieldIconColor: const Color(0xFFED1D24),
                  searchIconColor: const Color(0xFFED1D24),
                  autoFocus: true,
                  onSuffixTap: () {
                    setState(() {
                      textController.clear();
                    });
                  },
                  onSubmitted: (name) async {
                    if (name.isEmpty) {
                      listCount = 0;
                      currentPage = 0;
                      filmList.clear();
                      _loadMoreData();
                      return;
                    }
                    try {
                      listCount = 0;
                      currentPage = int.parse(name);
                      if (currentPage > 233 || currentPage <= 0) {
                        Fluttertoast.showToast(
                            msg: "区间范围:[1/233]",
                            toastLength: Toast.LENGTH_SHORT,
                            gravity: ToastGravity.BOTTOM,
                            timeInSecForIosWeb: 1,
                            backgroundColor: Colors.red,
                            textColor: Colors.white,
                            fontSize: 16.0);
                        return;
                      }
                      filmList.clear();
                      _loadMoreData();
                    } catch (e) {
                      final searchItem = await httpService.searchFilm(name);
                      if (searchItem != null) {
                        /*listCount += searchItem.length; 这样会原有的基础上进行增加*/
                        listCount = searchItem.length;
                        currentPage = 0;
                        filmList.clear();
                        filmList.addAll(searchItem);
                      }
                    }
                  },
                  style: const TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.w400),
                  boxShadow: false,
                ),
              ),
              const SizedBox(width: 5),
              Align(
                alignment: Alignment.centerRight,
                child: GestureDetector(
                  onTap: () {
                    dialog_m(context);
                  },
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 500),
                    alignment: Alignment.center,
                    height: 38.0,
                    width: 38.0,
                    curve: Curves.easeOut,
                    decoration: BoxDecoration(
                      color: const Color(0x33ED1D24),
                      borderRadius: BorderRadius.circular(30.0),
                    ),
                    child: SvgPicture.asset(
                      'assets/svg/Notice.svg',
                      height: 22,
                      width: 22,
                      color: const Color(0xFFED1D24),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 5),
              Align(
                alignment: Alignment.centerRight,
                child: GestureDetector(
                  onTap: () {
                    FilmSort(context);
                  },
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 500),
                    alignment: Alignment.center,
                    height: 38.0,
                    width: 38.0,
                    curve: Curves.easeOut,
                    decoration: BoxDecoration(
                      color: const Color(0x33ED1D24),
                      borderRadius: BorderRadius.circular(30.0),
                    ),
                    child: SvgPicture.asset(
                      'assets/svg/Sort.svg',
                      height: 22,
                      width: 22,
                      color: const Color(0xFFED1D24),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /*公告弹窗*/
  void dialog_m(BuildContext context) {
    return Dialogs.bottomMaterialDialog(
        msg: ApiConfig().getNotice(),
        title: BannerImages.appName,
        color: Colors.white,
        isScrollControlled: true,
        useRootNavigator: true,
        isDismissible: true,
        enableDrag: true,
        context: context,
        actions: [
          /*IconsButton(
            onPressed: () {
              Navigator.of(context).pop(['Test', 'List']);
            },
            text: 'ماقۇل',
            iconData: Icons.check_circle_outline,
            color: Colors.green,
            textStyle: const TextStyle(
                color: Colors.white, fontWeight: FontWeight.w900),
            iconColor: Colors.white,
          ),*/
          GestureDetector(
            onTap: () async {
              Navigator.of(context).pop(['Test', 'List']);
            },
            child: Container(
              margin: const EdgeInsets.only(top: 15),
              width: 270,
              height: 40,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black),
                borderRadius: const BorderRadius.all(Radius.circular(15)),
                color: Colors.pink.shade300,
              ),
              child: const Text(
                'مۇقۇمداش',
                style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w800,
                    fontSize: 12),
              ),
            ),
          ),
          GestureDetector(
            onTap: () async {
              await launch(APP_URL);
            },
            child: Container(
              margin: const EdgeInsets.only(top: 15),
              width: 270,
              height: 40,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black),
                borderRadius: const BorderRadius.all(Radius.circular(15)),
                color: Colors.pink.shade300,
              ),
              child: const Text(
                'APP چۈشۈرۈش',
                style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w800,
                    fontSize: 12),
              ),
            ),
          ),
        ]);
  }

  /*选择分类*/
  RadioGroupController categoryController = RadioGroupController();
  RadioGroupController contentTypeController = RadioGroupController();
  RadioGroupController sortTypeController = RadioGroupController();
  RadioGroupController yearController = RadioGroupController();

  /*主体*/
  final Map<String, int> categoryMap = {
    'بارلىق': -1,
    'ھەرىكەتلىك': 11,
    'ۋەقەلىك': 12,
    'تىياتىر': 13,
    'ئۇنىۋېرسال': 14,
    'مۇھەببەت': 15,
    'فانتازىيە': 16,
    'ۋەھىمىلىك': 17,
    'كارتون': 18,
    ' ئاپەت': 19,
  };
  late String selectedCategory = 'بارلىق';

  /*类别*/
  final Map<String, int> contentTypeMap = {
    'بارلىق': -1,
    'كىنو': 0,
    'قىسىملىق': 1,
    'ئۇنىۋېرسال': 2
  };
  late String selectedContentType = 'بارلىق';

  /*上线*/
  final Map<String, int> sortTypeMap = {
    'بارلىق': -1,
    'ئەڭ يېڭى': 1,
    'ئالقىشلىق': 2,
    'تەۋسىيە': 3
  };
  late String selectedSortType = 'بارلىق';

  /*日期*/
  final Map<String, int> yearMap = {
    'بارلىق': -1,
    '2024': 2024,
    '2023': 2023,
    '2022': 2022,
    '2021': 2021,
    '2020': 2020,
    '2019': 2019,
    '2018': 2018,
    '2017': 2017,
    '2016': 2016,
    '2015': 2015,
    '2015تىن بۇرۇن': 0
  };
  late String selectedyear = 'بارلىق';

  AwesomeDialog FilmSort(BuildContext context) {
    return AwesomeDialog(
      context: context,
      width: MediaQuery.of(context).size.width,
      animType: AnimType.scale,
      padding: const EdgeInsets.only(bottom: 15, left: 10, right: 10),
      dialogType: DialogType.noHeader,
      body: SortRadio(context),
    )..show();
    /*return Dialogs.bottomMaterialDialog(
        color: Colors.white,
        customViewPosition: CustomViewPosition.BEFORE_ACTION,
        context: context,
        customView: SingleChildScrollView(
            child: SortRadio(context),
          ),
      );*/
  }

  /*分类选择*/
  Widget SortRadio(BuildContext context) {
    return Column(
      children: [
        Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.only(bottom: 5, top: 0),
          child: const Text("--- تەرتىپ ---",
              style: TextStyle(
                  color: Color(0xFFED1D24),
                  fontWeight: FontWeight.w900,
                  fontSize: 12)),
        ),
        RadioGroup(
          controller: sortTypeController,
          values: sortTypeMap.keys.toList(),
          indexOfDefault: sortTypeMap.keys.toList().indexOf(selectedSortType),
          orientation: RadioGroupOrientation.horizontal,
          decoration: const RadioGroupDecoration(
            spacing: 1.0,
            labelStyle: TextStyle(
                color: Colors.black, fontSize: 12, fontWeight: FontWeight.w600),
            activeColor: Color(0xFFED1D24),
          ),
          onChanged: (sortTypeName) {
            setState(() {
              selectedSortType = sortTypeName;
              sortType = sortTypeMap[sortTypeName]!;
            });
          },
        ),
        const Divider(indent: 40, endIndent: 40, thickness: 0.6),
        Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.only(bottom: 5, top: 0),
          child: const Text("--- مەزمۇن ---",
              style: TextStyle(
                  color: Color(0xFFED1D24),
                  fontWeight: FontWeight.w900,
                  fontSize: 12)),
        ),
        RadioGroup(
          controller: contentTypeController,
          values: contentTypeMap.keys.toList(),
          indexOfDefault:
              contentTypeMap.keys.toList().indexOf(selectedContentType),
          orientation: RadioGroupOrientation.horizontal,
          decoration: const RadioGroupDecoration(
            spacing: 1.0,
            labelStyle: TextStyle(
                color: Colors.black, fontSize: 12, fontWeight: FontWeight.w600),
            activeColor: Color(0xFFED1D24),
          ),
          onChanged: (contentTypeName) {
            setState(() {
              selectedContentType = contentTypeName;
              contentType = contentTypeMap[contentTypeName]!;
            });
          },
        ),
        const Divider(indent: 40, endIndent: 40, thickness: 0.6),
        Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.only(bottom: 5, top: 0),
          child: const Text("--- تۈرلەر ---",
              style: TextStyle(
                  color: Color(0xFFED1D24),
                  fontWeight: FontWeight.w900,
                  fontSize: 12)),
        ),
        RadioGroup(
          controller: categoryController,
          values: categoryMap.keys.toList(),
          indexOfDefault: categoryMap.keys.toList().indexOf(selectedCategory),
          orientation: RadioGroupOrientation.horizontal,
          decoration: const RadioGroupDecoration(
            spacing: 1.0,
            labelStyle: TextStyle(
                color: Colors.black, fontSize: 12, fontWeight: FontWeight.w600),
            activeColor: Color(0xFFED1D24),
          ),
          onChanged: (categoryName) {
            setState(() {
              selectedCategory = categoryName;
              category = categoryMap[categoryName]!;
            });
          },
        ),
        const Divider(indent: 40, endIndent: 40, thickness: 0.6),
        Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.only(bottom: 5, top: 0),
          child: const Text("--- يىلى ---",
              style: TextStyle(
                  color: Color(0xFFED1D24),
                  fontWeight: FontWeight.w900,
                  fontSize: 12)),
        ),
        RadioGroup(
          controller: yearController,
          values: yearMap.keys.toList(),
          indexOfDefault: yearMap.keys.toList().indexOf(selectedyear),
          orientation: RadioGroupOrientation.horizontal,
          decoration: const RadioGroupDecoration(
            spacing: 1.0,
            labelStyle: TextStyle(
                color: Colors.black, fontSize: 12, fontWeight: FontWeight.w600),
            activeColor: Color(0xFFED1D24),
          ),
          onChanged: (yearName) {
            setState(() {
              selectedyear = yearName;
              year = yearMap[yearName]!;
            });
          },
        ),
        GestureDetector(
          onTap: () async {
            if (category != previousCategory ||
                contentType != previousContentType ||
                sortType != previousSortType ||
                year != previousYear) {
              /*print('更新了');*/
              /*判断有没有变化*/
              filmList.clear();
              listCount = 0;
              currentPage = 0;
              _loadMoreData();
              /*更新*/
              previousCategory = category;
              previousContentType = contentType;
              previousSortType = sortType;
              previousYear = year;
            }
            Navigator.of(context).pop(['Test', 'List']);
          },
          child: Container(
            margin: const EdgeInsets.only(top: 15),
            width: 270,
            height: 40,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border.all(color: Colors.black),
              borderRadius: const BorderRadius.all(Radius.circular(15)),
              color: Colors.pink.shade300,
            ),
            child: const Text(
              'مۇقۇمداش',
              style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w800,
                  fontSize: 12),
            ),
          ),
        ),
      ],
    );
  }

  /* Banner */
  Widget _banner(double height, double width) {
    return SingleChildScrollView(
        physics: const ClampingScrollPhysics(),
        child: Container(
          alignment: Alignment.center,
          child: SizedBox(
            width:
                MediaQuery.of(context).size.width > 500 ? 500 : double.infinity,
            child: Column(
              children: [
                /* 导航图 */
                BannerCarousel(
                  customizedIndicators: const IndicatorModel.animation(
                      width: 15,
                      height: 2,
                      spaceBetween: 3,
                      widthAnimation: 50),
                  height: height * 0.7,
                  borderRadius: 0,
                  margin: const EdgeInsets.all(0),
                  animation: true,
                  indicatorBottom: false,
                  disableColor: ColorConstants.primary_grey,
                  activeColor: ColorConstants.primary_red,
                  customizedBanners: [
                    GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => VideoPlayerM(
                                url: responseData['url1'], icon: '', title: ''),
                          ),
                        );
                      },
                      child: CachedNetworkImage(
                        imageUrl: responseData['img1'],
                        fit: BoxFit.cover,
                        errorWidget: (context, url, error) => Image.asset(
                            'assets/image/ic_load.png',
                            fit: BoxFit.cover),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => VideoPlayerM(
                                url: responseData['url2'], icon: '', title: ''),
                          ),
                        );
                      },
                      child: CachedNetworkImage(
                        imageUrl: responseData['img2'],
                        fit: BoxFit.cover,
                        errorWidget: (context, url, error) => Image.asset(
                            'assets/image/ic_load.png',
                            fit: BoxFit.cover),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => VideoPlayerM(
                                url: responseData['url3'], icon: '', title: ''),
                          ),
                        );
                      },
                      child: CachedNetworkImage(
                        imageUrl: responseData['img3'],
                        fit: BoxFit.cover,
                        errorWidget: (context, url, error) => Image.asset(
                            'assets/image/ic_load.png',
                            fit: BoxFit.cover),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => VideoPlayerM(
                                url: responseData['url4'], icon: '', title: ''),
                          ),
                        );
                      },
                      child: CachedNetworkImage(
                        imageUrl: responseData['img4'],
                        fit: BoxFit.cover,
                        errorWidget: (context, url, error) => Image.asset(
                            'assets/image/ic_load.png',
                            fit: BoxFit.cover),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => VideoPlayerM(
                                url: responseData['url5'], icon: '', title: ''),
                          ),
                        );
                      },
                      child: CachedNetworkImage(
                        imageUrl: responseData['img5'],
                        fit: BoxFit.cover,
                        errorWidget: (context, url, error) => Image.asset(
                            'assets/image/ic_load.png',
                            fit: BoxFit.cover),
                      ),
                    ),
                  ],
                ),
                /* 分类标题 */
                Container(
                  width: width,
                  height: 50,
                  margin: const EdgeInsets.only(right: 16, left: 16),
                  alignment: Alignment.centerRight,
                  child: Text(
                    'تەۋسىيە فىلىملەر',
                    textAlign: TextAlign.right,
                    style: GoogleFonts.itim(
                      textStyle: TextStyle(
                        fontFamily: 'MainFont',
                        color: ColorTween(
                          begin: const Color(0xFFED1D24),
                          end: const Color(0xFFED1F69),
                        ).lerp(0.5),
                        fontSize: 20,
                        fontWeight: FontWeight.w300,
                      ),
                    ),
                  ),
                ),
                /* 实现列表 */
                NotificationListener<ScrollNotification>(
                  onNotification: (scrollNotification) {
                    /*if (!isLoading &&
                  scrollNotification.metrics.pixels ==
                      scrollNotification.metrics.maxScrollExtent) {
                setState(() {
                  isLoading = true;
                  _loadMoreData(); //加载数据
                });
              }*/
                    return true;
                  },
                  child: RepaintBoundary(
                    child: Column(
                      children: [
                        Container(
                          margin: const EdgeInsets.only(
                              bottom: 8, left: 8, right: 8),
                          child: GridView.builder(
                            gridDelegate:
                                const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 3,
                              childAspectRatio: 0.65,
                            ),
                            //* 移除上方的空格 *//
                            padding: EdgeInsets.zero,
                            shrinkWrap: true,
                            controller: scrollController,
                            addAutomaticKeepAlives: false,
                            addRepaintBoundaries: false,
                            physics: const BouncingScrollPhysics(),
                            itemCount: listCount,
                            itemBuilder: (BuildContext context, int index) {
                              /*print('index $index');
                  print('items.length ' + listCount.toString());*/
                              /*if (index == filmList.length) {
                        return _buildProgressIndicator();
                      } else {*/
                              return GestureDetector(
                                onTap: () async {
                                  int id = filmList[index].id;
                                  if (filmList[index].type == 0) {
                                    /*旧方式（无法播放多级） --- 单集电影*/
                                    String title = filmList[index].name;
                                    String image = filmList[index].cover;
                                    String? url =
                                        await httpService.getVideoUrl(id);
                                    //await launch(url!); //打开浏览器
                                    if (url != null) {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => VideoPlayerM(
                                              url: url,
                                              icon: image,
                                              title: title),
                                        ),
                                      );
                                    }
                                  } else if (filmList[index].type == 1) {
                                    /*新方式（可预览多集数据） --- 多集电影*/
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => MoreVedio(id: id),
                                      ),
                                    );
                                  }
                                },
                                child: Container(
                                  margin: const EdgeInsets.symmetric(
                                      horizontal: 5, vertical: 5),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(16),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.grey.withOpacity(0.5),
                                        blurRadius: 1,
                                      ),
                                    ],
                                  ),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Expanded(
                                        child: ClipRRect(
                                          borderRadius: const BorderRadius.only(
                                            topLeft: Radius.circular(16),
                                            topRight: Radius.circular(16),
                                          ),
                                          child: CachedNetworkImage(
                                            imageUrl: filmList[index]
                                                .cover /*.replaceFirst('http://', 'https://')*/,
                                            fit: BoxFit.cover,
                                            memCacheWidth: 150,
                                            memCacheHeight: 160,
                                            width: 150,
                                            /*progressIndicatorBuilder: (context, url, downloadProgress) =>
                                      LinearProgressIndicator(value: downloadProgress.progress),*/
                                            placeholder: (context, url) =>
                                                Image.asset(
                                                    'assets/image/ic_load.png',
                                                    fit: BoxFit.cover),
                                            errorWidget:
                                                (context, url, error) =>
                                                    Image.asset(
                                              'assets/image/ic_load.png',
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                        ),
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: [
                                            Text(
                                              filmList[index].name,
                                              textAlign: TextAlign.right,
                                              maxLines: 1,
                                              overflow: TextOverflow.fade,
                                              style: GoogleFonts.cairo(
                                                  fontSize: 10,
                                                  fontWeight: FontWeight.bold),
                                            ),
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.center,
                                              children: [
                                                Container(
                                                  padding: const EdgeInsets
                                                      .symmetric(horizontal: 5),
                                                  decoration: BoxDecoration(
                                                    color:
                                                        Colors.deepPurpleAccent,
                                                    // 将背景颜色设置为半透明的黑色
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            6), // 将边框设置为圆角
                                                  ),
                                                  child: Text(
                                                    /*(Random().nextDouble() *
                                                          (9.9 - 5.0) +
                                                      5.0)
                                                  .toStringAsFixed(1)
                                                  .toString()*/
                                                    filmList[index]
                                                        .rate
                                                        .toString()
                                                        .trim(),
                                                    style: GoogleFonts.almendra(
                                                        fontSize: 12,
                                                        color: Colors.white),
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                    // 添加省略号
                                                    maxLines:
                                                        1, // 设置最大行数为1，即限制最大字符数量// 设置文本样式
                                                  ),
                                                ),
                                                Container(
                                                  decoration: BoxDecoration(
                                                    color: ColorTween(
                                                      begin: const Color(
                                                          0xFFED1D24),
                                                      end: const Color(
                                                          0xFFED1F69),
                                                    ).lerp(0.5),
                                                    // 将背景颜色设置为半透明的黑色
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            6), // 将边框设置为圆角
                                                  ),
                                                  padding:
                                                      const EdgeInsets.only(
                                                          left: 3,
                                                          right: 3,
                                                          top: 1,
                                                          bottom: 1),
                                                  margin: const EdgeInsets.only(
                                                      left: 3),
                                                  child: Text(
                                                    Strs(filmList[index]
                                                        .category_name
                                                        .trim()),
                                                    style: const TextStyle(
                                                        fontSize: 10,
                                                        fontWeight:
                                                            FontWeight.w500,
                                                        color: Colors.white),
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                    // 添加省略号
                                                    maxLines:
                                                        1, // 设置最大行数为1，即限制最大字符数量// 设置文本样式
                                                  ),
                                                ),
                                                /*const SizedBox(width: 4),
                                      const Icon(
                                        Icons.star,
                                        color: ColorConstants.primary_red,
                                        size: 16,
                                      ),*/
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              );
                              /*}*/
                            },
                          ),
                        ),
                        /*_buildProgressIndicator(),*/
                        Container(
                          margin: const EdgeInsets.only(top: 15),
                          decoration: const BoxDecoration(
                            borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(15),
                                topRight: Radius.circular(15)),
                          ),
                          child: EasyButton(
                            idleStateWidget: const Text(
                              '⇓ تېخىمۇ  كۆپ  فىلىملەر',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w800,
                                  fontSize: 14),
                            ),
                            loadingStateWidget: const CircularProgressIndicator(
                              strokeWidth: 3.0,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                Colors.white,
                              ),
                            ),
                            useWidthAnimation: true,
                            useEqualLoadingStateWidgetDimension: true,
                            width: double.infinity,
                            height: 50.0,
                            contentGap: 10,
                            buttonColor: Colors.pink.shade300,
                            borderRadius: 25,
                            onPressed: onButtonPressed,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}
